import {createRouter, createWebHashHistory, RouterOptions} from 'vue-router'
import routes from './router'
import useUserInfoStore from "../store/user";
import request from "../axios/axios";


const router = createRouter({
    history: createWebHashHistory(),
    routes,
} as RouterOptions)


// 路由守卫
router.beforeEach((to, from,next) => {
    const user = useUserInfoStore()
    if (to.path === '/login'){
        next()
    }else {
        const token = localStorage.getItem("token")
        if (!token) {
            next("/login")
        }else {
            request.get("/api/auth/info").then(res => {
                if (res.data.success){
                    user.setUserInfo(res.data.data)
                    next()
                }else {
                    next("/login")
                }
            })
        }
    }
})

export default router
